package ReadJmeterLog;

import ReadJmeterLog.bean.Nmon;
import org.junit.jupiter.api.Test;

import java.io.*;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

public class ReadNmon {

    public static void main(String[] args) {
        ReadNmon test1 = new ReadNmon();
        Map<String, Nmon> nmonMap;
        String path = "D://";
        String fileName = "jmeter.log";
        File file = test1.readFile(path,fileName);
        nmonMap = test1.readNmonInfo(file);
        System.out.println();
    }

    public File readFile(String path, String fileName){
        File file = new File(path + fileName);
        return file;
    }


    public Map<String,Nmon> readNmonInfo(File file) {

        Map<String,Nmon> nmonMap = new LinkedHashMap<>();
        Nmon nmon = null;

        try(BufferedReader bufferedReader = new BufferedReader(new FileReader(file))){
            String lineStr;
            String[] cpuStrings1 = new String[]{"CPUUser","CPUSys","CPUWait"};
            String[] cpuStrings2 = new String[]{"CPUIdle","CPUUse"};
            String[] procStrings = new String[]{"RunQueue","pswitch","syscall"};
            String[] memoryStrings = new String[]{"TotalMemUse","cached/memetotal","buffers/memtoal"};
            String[] netWorkStrings1 = new String[]{"eth0-write-KB/s","lo-write-KB/s"};
            String[] netWorkStrings2 = new String[]{"eth0-read-KB/s"};
            String[] diskStrings = new String[]{"TotalDiskRead","TotalDiskWrite","TotalDiskIO"};

            Map<String,String> timeAndIPMap;
            Map<String,String> cpuMap;
            Map<String,String> procMap;
            Map<String,String> memoryMap;
            Map<String,String> netWorkMap;
            Map<String,String> diskMap;

            //按行读取文件
            while((lineStr = bufferedReader.readLine()) != null){

                //跳过文件中的说明行，例如：--------------------------- CPU、Memory....
                if(lineStr.startsWith("-")){
                    continue;
                }

                //如果是监控信息的首行（可能有多组监控信息）
                if(lineStr.startsWith(">>>>>>>>> _")){

                    nmon = new Nmon();
                    timeAndIPMap = interceptTimeAndIp(lineStr);
                    nmon.setExecutionTime(timeAndIPMap.get("executionTime"));
                    nmon.setServerIP(timeAndIPMap.get("serverIP"));
                }
                //CPU信息
                else if(lineStr.startsWith("CPUUser")){
                    cpuMap = interceptCPUAndPROCAndMemoryAndNetWorkAndDisk(lineStr, cpuStrings1,"%");
                    nmon.setCPUUser(cpuMap.get("CPUUser"));
                    nmon.setCPUSys(cpuMap.get("CPUSys"));
                    nmon.setCPUWait(cpuMap.get("CPUWait"));
                }
                else if(lineStr.startsWith("CPUIdle")){
                    cpuMap = interceptCPUAndPROCAndMemoryAndNetWorkAndDisk(lineStr, cpuStrings2,"%");
                    nmon.setCPUIdel(cpuMap.get("CPUIdle"));
                    nmon.setCPUUse(cpuMap.get("CPUUse"));
                }
                //PROC
                else if(lineStr.startsWith("RunQueue")){
                    lineStr = lineStr + "      ";
                    procMap = interceptCPUAndPROCAndMemoryAndNetWorkAndDisk(lineStr, procStrings,"      ");
                    nmon.setRunQueue(procMap.get("RunQueue"));
                    nmon.setPswitch(procMap.get("pswitch"));
                    nmon.setSyscall(procMap.get("syscall"));
                }
                //Memory
                else if(lineStr.startsWith("TotalMemUse")){
                    memoryMap = interceptCPUAndPROCAndMemoryAndNetWorkAndDisk(lineStr, memoryStrings,"%");
                    nmon.setTotalMenUse(memoryMap.get("TotalMemUse"));
                    nmon.setCached_memetotal(memoryMap.get("cached/memetotal"));
                    nmon.setBuffers_memtoal(memoryMap.get("buffers/memtoal"));
                }
                //NetWork
                else if(lineStr.startsWith("eth0-write-KB/s")){
                    lineStr = lineStr + "      ";
                    netWorkMap = interceptCPUAndPROCAndMemoryAndNetWorkAndDisk(lineStr, netWorkStrings1,"      ");
                    nmon.setEth0_write_KB_s(netWorkMap.get("eth0-write-KB/s"));
                    nmon.setLo_write_KB_s(netWorkMap.get("lo-write-KB/s"));
                }
                else if(lineStr.startsWith("eth0-read-KB/s")){
                    netWorkMap = interceptCPUAndPROCAndMemoryAndNetWorkAndDisk(lineStr, netWorkStrings2,null);
                    nmon.setEth0_read_KB_s(netWorkMap.get("eth0-read-KB/s"));
                }
                //Disk
                else if(lineStr.startsWith("TotalDiskRead")){
                    diskMap = interceptCPUAndPROCAndMemoryAndNetWorkAndDisk(lineStr, diskStrings,"KB/s");
                    nmon.setTotalDiskRead(diskMap.get("TotalDiskRead"));
                    nmon.setTotalDiskWrite(diskMap.get("TotalDiskWrite"));
                    nmon.setTotalDiskIO(diskMap.get("TotalDiskIO"));

                    //读取完所有信息（CPU、MEM...Disk），将nmon类添加至map
                    nmonMap.put(nmon.getServerIP(),nmon);
                }
            }


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return nmonMap;
    }

    /**
     * 获取执行时间 和 被监控服务器IP地址
     * @param str 待截取的字符串
     * @return map
     * @Auther jiangboyang 20210501
     */
    public Map<String,String> interceptTimeAndIp(String str){
        //">>>>>>>>> _20210415999999_22.5.127.180.nmon >>>>>>>>>>>>"
        //掐头去尾
        str = str.substring(0,str.indexOf(".nmon"));
        str = str.substring(str.indexOf("_") + 1);
        //以"_"分隔，例如：20210415999999_22.5.127.180
        String[] strArray = str.split("_");
        Map<String,String> timeAndIPMap = new HashMap<>();
        timeAndIPMap.put("executionTime",strArray[0]);
        timeAndIPMap.put("serverIP",strArray[1]);
        return timeAndIPMap;
    }

    /**
     * 截取CPU、PROC、内存、网络、磁盘相关字段值
     * @param str 待截取的字符串
     * @param fieldNameStrings  字段名称
     * @param symbol 符号（%，KB/s,      -空格）
     * @return map
     * @Auther jiangboyang 20210501
     */
    public Map<String,String> interceptCPUAndPROCAndMemoryAndNetWorkAndDisk(String str, String[] fieldNameStrings, String symbol){
        String lintStr = str;
        Map<String,String> map = new HashMap<>();

        for(int i = 0; i < fieldNameStrings.length; i++){
            //从“字段=”开始截取，到“符号”结束
            if(symbol != null) {
                map.put(fieldNameStrings[i], lintStr.substring(lintStr.indexOf(fieldNameStrings[i] + "=") + (fieldNameStrings[i] + "=").length(), lintStr.indexOf(symbol)));
            }
            else {
                map.put(fieldNameStrings[i], lintStr.substring(lintStr.indexOf(fieldNameStrings[i] + "=") + (fieldNameStrings[i] + "=").length()));
            }
            //除最后一个字段，其余已取到的字符，需要从字符串中剔除
            if(i < fieldNameStrings.length - 1){
                lintStr = lintStr.substring(lintStr.indexOf(symbol) + symbol.length());
            }

        }
        return map;
    }


    @Test
    public void f(){
        String lintStr = "RunQueue=4.300      pswitch=27341.690      syscall=-1.000";
        String symbol = "      ";
//        lintStr = lintStr + "      ";
        String[] fieldNameStrings = new String[]{"RunQueue","pswitch","syscall"};
//        lintStr = lintStr.replaceAll("      "," ");
        System.out.println(lintStr);
        System.out.println(fieldNameStrings.length);
        for(int i = 0; i < fieldNameStrings.length; i++){
            if(symbol != null){
                System.out.println(lintStr.substring(lintStr.indexOf(fieldNameStrings[i] + "=") + (fieldNameStrings[i] + "=").length(), lintStr.indexOf(symbol)));
            }
            else {
                System.out.println(lintStr.substring(lintStr.indexOf(fieldNameStrings[i] + "=") + (fieldNameStrings[i] + "=").length()));
            }
            if(i < fieldNameStrings.length - 1){
                lintStr = lintStr.substring(lintStr.indexOf(symbol) + symbol.length());
            }

        }

//        System.out.println(lintStr.indexOf("      ") + "      ".length());
//        lintStr = lintStr.substring(lintStr.indexOf("      ") + "      ".length());
//        System.out.println(lintStr);
//        System.out.println(s.indexOf("%"));
//        System.out.println(s.indexOf("CPUUser=") + "CPUUser=".length() + s.indexOf("%"));
//        System.out.println( s.substring(s.indexOf("CPUUser=") + "CPUUser=".length(), s.indexOf("%"))  );
//        s = s.substring(s.indexOf("%") + 1);
//        System.out.println(s);
//        System.out.println(  s.substring(s.indexOf("CPUSys=") + "CPUSys=".length(),  s.indexOf("%")) );

    }

}
